package com.genersoft.iot.vmp.gb28181.third.callback;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.genersoft.iot.vmp.gb28181.bean.DeviceChannel;
import io.netty.util.concurrent.DefaultThreadFactory;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.net.ConnectException;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author XJW
 */
@Component
public class CallBackService {
    private Logger logger = LoggerFactory.getLogger(CallBackService.class);
    Executor processThreadPool = new ThreadPoolExecutor(2, 4,
            0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(1000),
            new DefaultThreadFactory("CallBack-"),
            new ThreadPoolExecutor.CallerRunsPolicy());
    @Autowired
    private CallBackProperties properties;

    public void channelUpate(List<DeviceChannel> channels) {
        processThreadPool.execute(()->{
            if (CollectionUtils.isEmpty(properties.getChannelUrl())
                    || CollectionUtils.isEmpty(channels)) {
                return;
            }
            String channelStr = JSON.toJSONString(channels);
            OkHttpClient client = new OkHttpClient();

            RequestBody requestBody = RequestBody.create(channelStr, MediaType.parse("application/json; charset=utf-8"));
            for (String url : properties.getChannelUrl()) {
                try {
                    Request request = new Request.Builder()
                            .post(requestBody)
                            .url(url)
                            .build();
                    Response response = client.newCall(request).execute();
                    if (response.isSuccessful()) {
                        String responseStr = response.body().string();
                        if (responseStr != null) {
                            JSONObject responseJSON = JSON.parseObject(responseStr);
                            logger.info("CallBackChennelUpdate response {}", responseJSON);
                        }
                    } else {
                        response.close();
                        Objects.requireNonNull(response.body()).close();
                    }
                } catch (ConnectException e) {
                    logger.error(String.format("连接CallBackChannelUpate失败: %s, %s", e.getCause().getMessage(), e.getMessage()));
                } catch (IOException e) {
                    logger.error(String.format("[ %s ]请求失败: %s", url, e.getMessage()));
                }
            }
        });
    }
}
